<!-- 登录页面 -->
<template>
    <div class="login-container">
        <!-- 顶部 -->
        <div class="top-switch">
            <SwitchDark />
            <LangSelect class="lang-select" />
        </div>
        <!-- 登录表单 -->
        <el-card class="login-card">
            <div class="login-title">
                <h2>{{ $t('title') }}</h2>
                <!-- <el-tag class="version">{{ version }}</el-tag> -->
            </div>
            <el-form
                ref="loginFormRef"
                :model="loginData"
                :rules="loginRules"
                class="login-form"
            >
                <el-form-item prop="username">
                    <div class="form-item">
                        <BaseSvgIcon
                            icon="user"
                            class="mg2"
                        />

                        <el-input
                            ref="username"
                            v-model="loginData.username"
                            class="form-input"
                            size="large"
                            :placeholder="$t('login.username')"
                            name="username"
                        />
                    </div>
                </el-form-item>

                <el-tooltip
                    :disabled="!isCapslock"
                    content="大写键已打开"
                    placement="right"
                >
                    <el-form-item prop="password">
                        <div class="form-item">
                            <BaseSvgIcon
                                icon="password"
                                class="mg2"
                            />

                            <el-input
                                v-model="loginData.password"
                                :placeholder="$t('login.password')"
                                :type="passwordVisible === false ? 'password' : 'input'"
                                size="large"
                                name="password"
                                @keyup="checkCapslock"
                                @keyup.enter="handleLogin"
                                class="form-input"
                            />
                            <span
                                class="right-icon"
                                @click="passwordVisible = !passwordVisible"
                            >
                                <BaseSvgIcon :icon-class="passwordVisible === false ? 'eye' : 'eye-open'" />
                            </span>
                        </div>
                    </el-form-item>
                </el-tooltip>

                <!-- 验证码 -->
                <el-form-item prop="captchaCode">
                    <div class="form-item">
                        <BaseSvgIcon
                            icon="captcha"
                            class="mg2"
                        />
                        <el-input
                            v-model="loginData.captchaCode"
                            auto-complete="off"
                            :placeholder="$t('login.captchaCode')"
                            class="form-input"
                            @keyup.enter="handleLogin"
                        />

                        <div class="captcha">
                            <Captcha
                                ref="verifyCode"
                                :strict="false"
                                :width="130"
                                :height="48"
                                @get-code="getCaptcha"
                            />
                        </div>
                    </div>
                </el-form-item>

                <el-button
                    :loading="loading"
                    type="primary"
                    class="login-button"
                    @click.prevent="handleLogin"
                    >{{ $t('login.login') }}
                </el-button>
            </el-form>
        </el-card>

        <!-- ICP备案 -->
        <div
            class="login-bottom"
            v-show="useAppStore().device == 'desktop'"
        >
            <p>ICP备案</p>
            <p>20240520</p>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { useWindowSize } from '@vueuse/core';

    // 状态管理依赖
    import type { FormInstance } from 'element-plus';
    import type { LocationQuery, LocationQueryValue } from 'vue-router';
    import { useUserStore } from '@/stores/modules/user';
    import { useAppStore } from '@/stores/modules/app';

    definePageMeta({
        layout: 'custom',
    });

    const appStore = useAppStore();
    const userStore = useUserStore();

    /**
     * 根据屏幕宽度切换设备模式
     */
    const WIDTH = 992; // 响应式布局容器固定宽度  大屏（>=1200px） 中屏（>=992px） 小屏（>=768px）
    const { width } = useWindowSize();
    watchEffect(() => {
        if (width.value < WIDTH) {
            appStore.toggleDevice('mobile');
        } else {
            appStore.toggleDevice('desktop');
        }
    });

    const loading = ref(false); // 按钮loading
    const isCapslock = ref(false); // 是否大写锁定
    const passwordVisible = ref(false); // 密码是否可见
    const captchaBase64 = ref(); // 验证码图片Base64字符串
    const loginFormRef = ref<FormInstance>(); // 登录表单ref
    const { t } = useI18n(); // 国际化

    const loginData = ref({
        username: 'admin',
        password: '123456',
        captchaCode: '',
    });
    const loginRules = computed(() => {
        const language = useCookie('language');

        return {
            username: [
                {
                    required: true,
                    trigger: 'blur',
                    message: t('login.usernamePlaceholder'),
                },
            ],
            password: [
                {
                    trigger: 'blur',
                    required: true,
                    message: t('login.passwordPlaceholder'),
                },
            ],
            captchaCode: [
                {
                    required: true,
                    trigger: 'blur',
                    message: t('login.captchaCodePlaceholder'),
                },
            ],
        };
    });

    /**
     * 检查输入大小写状态
     * @param e
     */
    const checkCapslock = (e: KeyboardEvent) => {
        const { key } = e;
        isCapslock.value = (key && key.length === 1 && key >= 'A' && key <= 'Z') as boolean;
    };

    /**
     * 获取验证码
     */
    const getCaptcha = (code: string) => {
        // getCaptchaApi().then(({ data }) => {
        //     loginData.value.captchaKey = data.captchaKey;
        //     captchaBase64.value = data.captchaBase64;
        // });
        // 模拟

        loginData.value.captchaCode = code;
    };

    const route = useRoute();
    const router = useRouter();
    const verifyCode = ref();
    // const userStore = useUserStore();
    /**
     * 登录
     */
    const handleLogin = () => {
        loginFormRef.value?.validate((valid: boolean) => {
            if (valid) {
                loading.value = true;

                console.log('登录');

                userStore
                    .login(loginData.value)
                    .then(() => {
                        const query: LocationQuery = route.query;

                        const redirect = (query.redirect as LocationQueryValue) ?? '/';

                        const otherQueryParams = Object.keys(query).reduce((acc: any, cur: string) => {
                            if (cur !== 'redirect') {
                                acc[cur] = query[cur];
                            }
                            return acc;
                        }, {});

                        router.push({ path: redirect, query: otherQueryParams });
                    })
                    .catch(() => {
                        // 验证失败，重新生成验证码

                        verifyCode.value.refreshCode();
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            }
        });
    };
</script>

<style lang="scss" scoped>
    .dark .login-container {
        background: url('@/assets/images/login-bg-dark.jpg') no-repeat center right;
    }

    .login-container {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        overflow-y: auto;
        background: url('@/assets/images/login-bg.jpg') no-repeat center right;

        .top-switch {
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            width: 100%;
            padding: 0.75rem;

            .lang-select {
                margin-left: 0.5rem;
                cursor: pointer;
            }
        }

        .login-card {
            width: 25rem;
            background-color: transparent;
            border-style: none;
            border-radius: 4%;
        }

        .login-title {
            position: relative;
            text-align: center;

            .version {
                position: absolute;
                top: 0;
                right: 0;
                margin-left: 0.25rem;
            }
        }

        .login-form {
            padding: 30px 10px;

            .captcha {
                position: absolute;
                top: 0;
                right: 0;

                .el-image {
                    flex: 1;
                    height: 48px;
                    cursor: pointer;
                }

                .image-slot {
                    display: flex;
                    align-items: center;
                    justify-content: right;
                    width: 100%;
                    height: 100%;
                    font-size: 18px;
                    color: var(--el-text-color-secondary);
                    background: var(--el-fill-color-light);

                    svg {
                        margin-right: 10px;
                    }
                }
            }

            .login-button {
                width: 100%;
                margin-bottom: 30px;
            }
        }

        .form-item {
            display: flex;
            align-items: center;
            width: 100%;

            .mg2 {
                margin: 0 0.5rem;
            }

            .form-input {
                flex: 1;
                height: 48px;
            }

            .right-icon {
                margin-right: 0.5rem;
                cursor: pointer;
            }
        }
    }

    .el-form-item {
        background: var(--el-input-bg-color);
        border: 1px solid var(--el-border-color);
        border-radius: 5px;
    }

    .login-bottom {
        position: absolute;
        bottom: 0.25rem;
        font-size: 10px;
        text-align: center;
    }

    :deep(.el-input) {
        .el-input__wrapper {
            padding: 0;
            background-color: transparent;
            box-shadow: none;

            &.is-focus,
            &:hover {
                box-shadow: none !important;
            }

            input:-webkit-autofill {
                transition: background-color 1000s ease-in-out 0s; /* 通过延时渲染背景色变相去除背景颜色 */
            }
        }
    }
</style>
